import React, {Component} from 'react';
import {View, Text, TouchableOpacity, Image, TextInput, Platform, Button} from 'react-native';
import SvgUri from 'react-native-svg-uri';
import {pxToDp} from '../../../utils/stylesKits';
import {male, female} from '../../../res/fonts/iconSvg';
import {Input} from 'react-native-elements';
import DateTimePicker from '@react-native-community/datetimepicker';
import THButton from '../../../components/THButton';
import * as ImagePicker from 'expo-image-picker'
import * as Location from 'expo-location';


import {inject, observer} from 'mobx-react';
import {Toast} from "react-native-toast-notifications";
import dayjs from "dayjs";
import {updateUser} from "../../../utils/request";

const isIOS = Platform.OS === 'ios'

@inject( 'store')
@observer
class UserInfo extends Component {
  state = {
    showDatePicker: false,
    userId: '',
    phone: '',
    user: {
      // 昵称
      nickname: '',
      // 性别
      gender: '男',
      // 生日
      birthday: '',
      // 地址
      city: '',
      // 头像
      header: '',
      // 经度
      lng: '',
      // 纬度
      lat: '',
      // 详细地址
      address: '',
      // 用户当前位置
      userLocation: null,
    }
  };

  constructor(props) {
    super(props);
    const store = props.store;
    this.state = {
      ...this.state,
      user: {...store.info},
      userId: store.userId,
      phone: store.mobile,
      // showDatePicker: !store.info.birthday
    }
  }

  componentDidMount() {
    this.getLocationPermission();
  }

  getLocationPermission = async () => {
    const {status} = await Location.requestForegroundPermissionsAsync()
    if (status !== 'granted') {
      console.log('Permission to access location was denied');
      return;
    }
    this.getCurrentLocation();
  };

  getCurrentLocation = async () => {
    const {coords} = await Location.getCurrentPositionAsync({});
    this.updateUser({userLocation: coords})
  };

  updateUser(user = {}, append = {}) {
    this.setState({
      user: {...this.state.user, ...user},
      ...append,
    })
    this.props.store.updateInfo(user)
  }

  /**
   * 选择生日
   * @param event
   * @param selectedDate
   */
  onBirthday(event, selectedDate) {
    if (selectedDate){
      const currentDate = dayjs(selectedDate).format('YYYY-MM-DD')
      if (isIOS){
        this.updateUser({birthday: currentDate})
      }else {
        this.updateUser({birthday: currentDate}, { showDatePicker: false })
      }
      console.log('onBirthday', selectedDate, currentDate)
    }
  }

  /**
   * IOS 中确认完成生日选择
   */
  onConfirmBirthday(){
    this.setState({ showDatePicker: false })
  }


  // 选择性别
  chooseGender = (gender) => {
    this.updateUser({gender});
  };

  showDatePicker(){
    console.log('showDatePicker')
    this.setState({ showDatePicker: true })
  }

  // 设置头像
  chooseHeadImg = async () => {
    // 1. 校验用户昵称 生日 当前地址 city
    // 2. 使用图片裁剪插件
    // 3. 将选择好的图片上传到后台
    // 4. 数据提交到后台,完成信息填写
    // 5. 成功 -> 执行极光的注册 , 极光的登录
    // 跳转到交友的首页
    // const image = await ImagePicker.openPicker({
    //   width: 300,
    //   height: 300,
    //   cropping: true,
    // });
    try {
      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.All,
        base64: true
      })
      if (result.canceled || !result.assets.length) {
        Toast.show('请选择头像', {duration: 1500})
        return
      }
      const asset = result.assets[0]
      // console.log('asset', asset)
      this.updateUser({header: asset.base64})

    } catch (e) {
      console.error('chooseHeadImg', e)

    }

  }

  onSave(){
    const {nickname, birthday, header} = this.state.user;
    console.log('nickname', nickname, birthday)
    if (!nickname || !birthday) {
      return Toast.show('昵称或者生日不合法', {
        duration: 1500,
      });
    }
    if (!header){
      return Toast.show('请选择头像', {
        duration: 1500,
      });
    }

    return updateUser(this.state.phone, {...this.state.user, isNew: false })
        .then(()=>{
          this.props.navigation.navigate('Home');
          // this.props.navigation.reset({
          //   routes: [{name: 'Tabbar'}],
          // });
        })

  }

  render() {
    const {showDatePicker} = this.state;
    const {gender, nickname, birthday, city, userLocation, header,} = this.state.user;

    return (
        <View style={{backgroundColor: '#fff', flex: 1, padding: 20}}>
          <Text>完善个人资料</Text>

          {/* 2.0 性别 开始 */}
          <View style={{marginTop: pxToDp(20)}}>
            <Text>性别</Text>
            <View
                style={{
                  width: '60%',
                  flexDirection: 'row',
                  alignSelf: 'center',
                  justifyContent: 'space-around',
                }}
            >
              <TouchableOpacity
                  onPress={this.chooseGender.bind(this, '男')}
                  style={{
                    width: pxToDp(60),
                    height: pxToDp(60),
                    borderRadius: pxToDp(30),
                    justifyContent: 'center',
                    alignItems: 'center',
                    backgroundColor: gender === '男' ? 'cyan' : '#eee',
                  }}
              >

                <SvgUri svgXmlData={male} width="34" height="34"/>

              </TouchableOpacity>
              <TouchableOpacity
                  onPress={this.chooseGender.bind(this, '女')}
                  style={{
                    width: pxToDp(60),
                    height: pxToDp(60),
                    borderRadius: pxToDp(30),
                    justifyContent: 'center',
                    alignItems: 'center',
                    backgroundColor: gender === '女' ? 'cyan' : '#eee',
                  }}
              >
                <SvgUri svgXmlData={female} width="34" height="34"/>
              </TouchableOpacity>
            </View>
          </View>
          {/* 2.0 性别 结束 */}

          {/* 3.0 昵称 开始 */}
          <Text>昵称</Text>
          <View>
            <Input
                value={nickname}
                placeholder="请设置昵称"
                onChangeText={(nickname) => {
                  this.updateUser({nickname});
                }}
            />
          </View>
          {/* 3.0 昵称 结束 */}

          {/* 4.0 日期 开始 */}
          <Text>生日</Text>
          <View style={{width: '100%', minHeight: 50, paddingTop: 10}}>
            <TouchableOpacity onPress={this.showDatePicker.bind(this)}>
              <View style={{width: '100%'}}>
                <Text>{ birthday || '请设置生日'}</Text>
                {
                  showDatePicker ? <DateTimePicker
                      value={birthday ? new Date(birthday) : new Date()} // 设置初始日期
                      mode="date" // 设置模式为日期选择模式
                      display="spinner" // 设置显示为下拉菜单模式
                      onChange={this.onBirthday.bind(this)}
                  /> : null
                }
                {
                  showDatePicker && isIOS ?
                      <Button onPress={this.onConfirmBirthday.bind(this)} title="确定" /> : null
                }
              </View>
            </TouchableOpacity>
          </View>

          {/* 4.0 日期 结束 */}

          {/* 5.0 头像 */}
          <Text>头像</Text>
          <View style={{width: '50%', height: pxToDp(80), alignSelf: "flex-start", paddingTop: 10, paddingBottom: 10}}>
            <TouchableOpacity onPress={this.chooseHeadImg.bind(this)}>
              <Image style={{
                width: pxToDp(80),
                height: pxToDp(80),
                borderRadius: pxToDp(40),
                borderWidth: 1,
                backgroundColor: '#efefef'
              }}
                     source={{ uri: `data:image/png;base64,${header}` }}
              />
            </TouchableOpacity>
          </View>
          <View style={{width: '50%', height: 80, alignSelf: "center", marginTop: 20}}>
            <THButton onPress={this.onSave.bind(this)}>保存</THButton>
          </View>
        </View>
    );
  }
}

export default UserInfo;
